package xnj.lazydog.btcontroller.ControlViews;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import xnj.lazydog.btcontroller.MyViews.DataPackView;
import xnj.lazydog.btcontroller.MyViews.PageView;
import xnj.lazydog.btcontroller.MyViews.PercentView;
import xnj.lazydog.btcontroller.ObjectFile.ObjectFile;
import xnj.lazydog.btcontroller.R;

public class DataPackActivity extends Activity {

    PageView pageView;
    PercentView txPercentView;
    PercentView rxPercentView;

    ImageView backButton;
    ImageView helpButton;
    DataPackView [] txDataPackViews = new DataPackView[5];
    DataPackView [] rxDataPackViews = new DataPackView[5];

    TextView txDataLength , rxDataLength;

    TextView [] txDataLabels = new TextView[5];
    TextView [] rxDataLabels = new TextView[5];

    RadioGroup trans_mode_group ;
    RadioButton []trans_mode_buttons=new RadioButton[3];

    EditText period_always;
    EditText period_on_touch;
    EditText times_repeat;

    Project project;

    String file_name = "123.pro";

    @Override
    protected void onCreate( Bundle savedInstanceState) {
        super.onCreate(savedInstanceState) ;
        setContentView(R.layout.datapack_layout);
        pageView = new PageView(this,R.id.data_pack_parent,R.id.data_pack_view_parent,new int[]{
                R.drawable.tx_data_pack_b,R.drawable.rx_data_pack_b,R.drawable.set_data_pack_b
        },0);

        file_name = getIntent().getStringExtra("fileName");

        project = (Project) ObjectFile.loadObject(this,file_name);

        if(project==null) {
            project = new Project();
        }

        backButton = findViewById(R.id.data_pack_back_button);
        helpButton = findViewById(R.id.data_pack_help);
        txPercentView = findViewById(R.id.percent_view);
        rxPercentView = findViewById(R.id.rx_percent_view);

        txDataLength = findViewById(R.id.tx_data_pack_length);
        rxDataLength = findViewById(R.id.rx_data_pack_length);

        period_always = findViewById(R.id.trans_always_period);
        period_on_touch = findViewById(R.id.trans_on_touch_period);
        times_repeat = findViewById(R.id.trans_repeat_times);

        trans_mode_group = findViewById(R.id.trans_mode_group);
        trans_mode_buttons[0] = findViewById(R.id.trans_mode_always);
        trans_mode_buttons[1] = findViewById(R.id.trans_mode_listener);
        trans_mode_buttons[2] = findViewById(R.id.trans_mode_on_touch);

        txDataPackViews[0]= findViewById(R.id.tx_data_pack_view_bool);
        txDataPackViews[1]= findViewById(R.id.tx_data_pack_view_byte);
        txDataPackViews[2]= findViewById(R.id.tx_data_pack_view_short);
        txDataPackViews[3]= findViewById(R.id.tx_data_pack_view_int);
        txDataPackViews[4]= findViewById(R.id.tx_data_pack_view_float);

        rxDataPackViews[0]= findViewById(R.id.rx_data_pack_view_bool);
        rxDataPackViews[1]= findViewById(R.id.rx_data_pack_view_byte);
        rxDataPackViews[2]= findViewById(R.id.rx_data_pack_view_short);
        rxDataPackViews[3]= findViewById(R.id.rx_data_pack_view_int);
        rxDataPackViews[4]= findViewById(R.id.rx_data_pack_view_float);

        txDataLabels[0]  = findViewById(R.id.tx_data_pack_nn_bool);
        txDataLabels[1]  = findViewById(R.id.tx_data_pack_nn_byte);
        txDataLabels[2]  = findViewById(R.id.tx_data_pack_nn_short);
        txDataLabels[3]  = findViewById(R.id.tx_data_pack_nn_int);
        txDataLabels[4]  = findViewById(R.id.tx_data_pack_nn_float);

        rxDataLabels[0]  = findViewById(R.id.rx_data_pack_nn_bool);
        rxDataLabels[1]  = findViewById(R.id.rx_data_pack_nn_byte);
        rxDataLabels[2]  = findViewById(R.id.rx_data_pack_nn_short);
        rxDataLabels[3]  = findViewById(R.id.rx_data_pack_nn_int);
        rxDataLabels[4]  = findViewById(R.id.rx_data_pack_nn_float);

        for(int i=0;i<txDataPackViews.length;i++)
        {
            txDataPackViews[i].initDataPackView(txPercentView.colors[1+i],i,project.txData[i],project.values[0][i],txDataViewListener);
            rxDataPackViews[i].initDataPackView(rxPercentView.colors[1+i],i,project.rxData[i],project.values[1][i],rxDataViewListener);
        }

        trans_mode_group.check(trans_mode_buttons[project.transMode].getId());
        String period = ""+project.transPeriodMs;
        period_always.setText(period);
        period = ""+project.controlPeriodMs;
        period_on_touch.setText(period);
        period = ""+project.repeatTimes;
        times_repeat .setText(period);

        for(int i=0;i<3;i++)
        {
            final int index = i;
            trans_mode_buttons[i].setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if(isChecked)
                    {
                        project.transMode = index;
                    }
                }
            });
        }


        period_always.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if("".equals(s.toString()))
                    return;
                int ms = Integer.parseInt(s.toString());
                if(ms>=10)
                {
                    if(ms<=10000)
                        project.transPeriodMs  = ms;
                    if(project.elements!=null)
                    for(ViewOptions vp:project.elements)
                    {
                        if(vp!=null&&vp.uiType==ViewOptions.UI_TYPE_PLOT)
                        {
                            vp.ms_per_data = ms;
                        }
                    }
                   else
                    {
                        Toast.makeText(DataPackActivity.this, "传输间隔不可大于10秒", Toast.LENGTH_SHORT).show();
                        period_always.setText("10000");
                    }
                }else
                    Toast.makeText(DataPackActivity.this,"传输间隔不可小于10毫秒",Toast.LENGTH_SHORT).show();
            }
            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        period_always.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(!hasFocus)
                {
                    //Log.w(TAG, "onFocusChange");
                    if("".equals(period_always.getText().toString()))
                        period_always.setText("50");
                    try {
                        int ms= Integer.parseInt(period_always.getText().toString());
                        if(ms<10) {
                            period_always.setText("10");
                            Toast.makeText(DataPackActivity.this,"传输间隔不可小于10毫秒",Toast.LENGTH_SHORT).show();
                        }
                    }catch (NumberFormatException e)
                    {
                        e.printStackTrace();
                        period_always.setText("50");
                    }
                }
            }
        });
        period_on_touch.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(!hasFocus)
                {
                    //Log.w(TAG, "onFocusChange");
                    if("".equals(period_on_touch.getText().toString()))
                        period_on_touch.setText("50");
                    try {
                        int ms= Integer.parseInt(period_on_touch.getText().toString());
                        if(ms<10) {
                            period_on_touch.setText("10");
                            Toast.makeText(DataPackActivity.this,"传输间隔不可小于10毫秒",Toast.LENGTH_SHORT).show();
                        }
                    }catch (NumberFormatException e)
                    {
                        e.printStackTrace();
                        period_on_touch.setText("50");
                    }
                }
            }
        });

        period_on_touch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if("".equals(s.toString()))
                    return;
                int ms = Integer.parseInt(s.toString());
                if(ms>=10)
                {
                    if(ms<=10000)
                        project.controlPeriodMs  = ms;
                    else
                    {
                        Toast.makeText(DataPackActivity.this, "传输间隔不可大于10秒", Toast.LENGTH_SHORT).show();
                        period_on_touch.setText("10000");
                    }
                }else {
                    Toast.makeText(DataPackActivity.this, "传输间隔不可小于10毫秒", Toast.LENGTH_SHORT).show();
                }
            }
            @Override
            public void afterTextChanged(Editable s) {
            }
        });


        times_repeat.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(!hasFocus)
                {
                    //Log.w(TAG, "onFocusChange");
                    if("".equals(times_repeat.getText().toString()))
                        times_repeat.setText("0");
                    try {
                        Integer.parseInt(times_repeat.getText().toString());
                    }catch (NumberFormatException e)
                    {
                        e.printStackTrace();
                        times_repeat.setText("0");
                    }
                }
            }
        });

        times_repeat.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if("".equals(s.toString()))
                    return;


                int ms=0;
                try {
                    ms = Integer.parseInt(s.toString());
                }catch (NumberFormatException e)
                {
                    e.printStackTrace();
                    times_repeat.setText("0");
                }
                if(ms<=20)
                {
                    project.repeatTimes = ms;

                }else {
                    Toast.makeText(DataPackActivity.this, "重复次数不得超过20次,否则会增加额外消耗", Toast.LENGTH_SHORT).show();
                    times_repeat.setText("20");
                }
            }
            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        helpButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bigSmall(v, new Runnable() {
                    @Override
                    public void run() {   //// 直接跳转到 帮助界面
                       Intent intent = new Intent(DataPackActivity.this,DataPackHelpActivity.class);
                       startActivity(intent);
                    }
                });
            }
        });

        rxPercentView.setData(project.getRxChannelBytes());
        txPercentView.setData(project.getTxChannelBytes());
        updateTxDataLabels();
        updateRxDataLabels();


    }

    @Override
    protected void onDestroy() {

        ObjectFile.saveObject(this,file_name,project);
        super.onDestroy();
    }


    void  bigSmall(final View view, final Runnable runnable)
    {
        Animation a = AnimationUtils.loadAnimation(this,R.anim.big_small);
        final Animation b = AnimationUtils.loadAnimation(this,R.anim.big_small_2);

        a.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }
            @Override
            public void onAnimationEnd(Animation animation) {
                view.startAnimation(b);
                runnable.run();
            }
            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
        view.startAnimation(a);
    }


    void updateTxDataLabels()
    {
        int sum=3;
        String str;
        int [] d = project.getTxChannelBytes();

        for(int i=0;i<txDataLabels.length;i++)
        {
            str = DataPackView.DATA_TYPE_NAMES[i].toLowerCase()+"\n"+d[1+i]+"字节";
            txDataLabels[i].setText(str);
            sum+=d[1+i];
        }
        str = "发送数据包 -- 共 "+sum+" 字节";
        txDataLength.setText(str);
    }

    void updateRxDataLabels()
    {
        String str;
        int sum = 3;
        int [] d = project.getRxChannelBytes();
        for(int i=0;i<rxDataLabels.length;i++)
        {
            str = DataPackView.DATA_TYPE_NAMES[i].toLowerCase()+"\n"+d[1+i]+"字节";
            rxDataLabels[i].setText(str);
            sum+=d[1+i];
        }
        str = "接收数据包 -- 共 "+sum+" 字节";
        rxDataLength.setText(str);
    }
    private static final String TAG = "DataPackActivity";
    DataPackView.DataViewListener txDataViewListener = new DataPackView.DataViewListener() {
        @Override
        public void onAddNewData(int type, int index, String name) {
            Log.w(TAG, "onAddNewData: type:"+type+"  index:"+index+"  str:"+name);
            txPercentView.setData(project.getTxChannelBytes());
            updateTxDataLabels();
        }
        @Override
        public void onDeleteData(int type, int index) {
            Log.w(TAG, "onDeleteData: type:"+type+"  index:"+index);
            txPercentView.setData(project.getTxChannelBytes());
            updateTxDataLabels();
            project.changeLinkMapAfterDelete(0,type,index);
        }
        @Override
        public void onEditDataName(int type, int index, String name) {
            Log.w(TAG, "onEditData: type:"+type+"  index:"+index+"  str:"+name);

        }
    };
    DataPackView.DataViewListener rxDataViewListener = new DataPackView.DataViewListener() {
        @Override
        public void onAddNewData(int type, int index, String name) {
            Log.w(TAG, "onAddNewData: type:"+type+"  index:"+index+"  str:"+name);

            rxPercentView.setData(project.getRxChannelBytes());
            updateRxDataLabels();
        }
        @Override
        public void onDeleteData(int type, int index) {
            Log.w(TAG, "onDeleteData: type:"+type+"  index:"+index);
            rxPercentView.setData(project.getRxChannelBytes());
            updateRxDataLabels();
            project.changeLinkMapAfterDelete(1,type,index);
        }
        @Override
        public void onEditDataName(int type, int index, String name) {
            Log.w(TAG, "onEditData: type:"+type+"  index:"+index+"  str:"+name);

        }
    };

}
